# -*- encoding: utf-8 -*-

"""
@File:      netstat.py
@Time:      2023/05/09
@Author:    sunqingwei
@Version:   1.0
@Contact:   sunqingwei@uniontech.com
@License:   Mulan PSL v2
"""

from common.sysinfo import SysInfo


class Netstat():
    """
    Common def for 2.
    """

    def __init__(self):
        self.cmd = SysInfo.cmd()

    def kill_port(self, port, host="local", ignore_status=True):
        '''
        Kill the process that occupies the port
        port: port num
        example:kill(8080)
        return:None
        '''
        exit_status, pid = self.cmd(
            "netstat -lntup | grep %s | awk '{print $NF}' | awk -F '/' '{print $1}'" % port,
            ignore_status=ignore_status)
        if pid:
            self.cmd(f'kill -9 {pid}', ignore_status=ignore_status)

    def get_port_status(self, port, host="local", ignore_status=False):
        '''
        get status of port
        port: port num
        example: get_status(8080)
        return: status
        '''
        status, output = self.cmd("netstat -lntup | grep %s | awk '{print $6}'" % port,
                                  ignore_status=ignore_status)
        return output
